package com.magima.utils.image;


import android.content.Context;
import android.widget.ImageView;


public class FakeGifUtil {
	private static PlayGifTask mGifTask;
	
	public static void setGif(ImageView img, Context context, int[] rIds, long delay){
		mGifTask = new PlayGifTask(img, rIds, delay);
		mGifTask.start();
	}

	public static void stopGif(){
		if(mGifTask != null)
			mGifTask.stop();
	}
	
	private static class PlayGifTask implements Runnable {
        private int i = 0;
        private ImageView iv;
        private int[] rIds;
        private long delay;

        public PlayGifTask(ImageView iv, int[] rIds, long delay) {
            this.iv = iv;
            this.rIds = rIds;
            this.delay = delay;
        }

        @Override
        public void run() {
        	if(iv == null || rIds == null || rIds.length == 0){
        		return;
        	}
        	
            if ( i >= rIds.length)
            	i = 0;

            synchronized (iv) {
        	    if(iv == null || rIds == null || rIds.length == 0) {
    			    return;
	    	    }
		        iv.setImageResource(rIds[i]);
            }
            
        	i++;
            synchronized (iv) {
                if ( iv == null ) {
                    return;
                }
                iv.postDelayed(this, delay);
            }
        }
        
        public void start() {
            iv.post(this);
        }
        
        public void stop() {
            if(null != iv){
            	iv.removeCallbacks(this);
                iv = null;
            }
            
            if(null != rIds) {
            	rIds = null;
            }
        }
    }
}
